//
//  EvetnSearchViewController.m
//  Runone
//
//  Created by runone02 on 16/9/1.
//  Copyright © 2016年 runone. All rights reserved.
//

#import "EvetnSearchViewController.h"
#import "UIView+Common.h"
#import "AppDelegate.h"
#import "MJRefresh.h"
#import "RequestGinsengModel.h"
#import "RequestHelper.h"
#import "ReportEvent.h"
#import "TollEvent.h"
#import "EventDetailModel.h"
#import "CJCalendarViewController.h"
#import "CurrentEvent.h"
#import "SVProgressHUD.h"
#import "PromptUtil.h"
#import "UIView+Message.h"
#import "MJExtension.h"
#import "EventCell.h"
#import "TollEvent.h"
#import "ReportEvent.h"
#import "AppConstants.h"
#import "HistoryEventDeatilController.h"
#import "TollViewController.h"
#import "CurrentContructDetailController.h"
#import "HistoryDetailViewController.h"
#import "ComfirnDeatilController.h"
#import "EditDetailViewController.h"


#define   kScreenWidth   [UIScreen mainScreen].bounds.size.width
#define   PageSize       10
@interface EvetnSearchViewController ()<UISearchBarDelegate,UITableViewDelegate,UITableViewDataSource,CalendarViewControllerDelegate>
@property (strong, nonatomic) UISearchBar *searchBar;

@property (strong, nonatomic) NSString *textString;

@property (strong, nonatomic) UITableView *tableView;

@property (assign, nonatomic) NSInteger currentPageIndex;

@property (strong, nonatomic) NSMutableArray *searchDataArray;

@property (copy, nonatomic) NSString *lastEventUID;

@property (assign, nonatomic) NSString *searchWay;

@property (copy, nonatomic) NSString *searchContent;
@property (nonatomic,strong)PromptUtil *popMessage;
@property (nonatomic,strong)UIView *meesageV;

@property (nonatomic, strong)UIButton *calendarBtn;

//@property (nonatomic, strong) UITableView *tableView;

@end

@implementation EvetnSearchViewController

static NSString *cellID = @"searchCell";
#pragma mark - laZy

//-(UITableView *)tableView {
//    if (_tableView == nil) {
//        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 64, self.view.bounds.size.width, self.view.bounds.size.height)];
//            _tableView.dataSource = self;
//            _tableView.delegate   = self;
//            _tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
//            [_tableView registerClass:[EventCell class] forCellReuseIdentifier:cellID];
////            [self.view addSubview:_tableView];
////            _tableView.hidden  = YES;
//    }
//    return _tableView;
//}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = kROLightFrayTextColor;
    _searchDataArray = [[NSMutableArray alloc] init];
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.currentPageIndex = 1;
    self.searchWay = @"1";
    //设置UI
    [self configNavitationBar];
    [self configTableView];
    [self configCalendarBtn];
}
- (void) viewWillAppear:(BOOL)animated {
    [super viewWillAppear:YES];
    self.tabBarController.tabBar.hidden = YES;
    [_searchBar resignFirstResponder];
}
- (void)configNavitationBar {
    _searchBar = [[UISearchBar alloc] init];
    _searchBar.placeholder = @"请输入搜索的关键字";
    self.navigationItem.titleView = _searchBar;
    _searchBar.delegate = self;
    [_searchBar becomeFirstResponder];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:[[UIView alloc] init]];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"取消" style:UIBarButtonItemStylePlain target:self action:@selector(navigationBackClick)];
}
- (void)navigationBackClick {
    [self.navigationController popViewControllerAnimated:YES];
}
- (void) calendarBtnClick {
    CJCalendarViewController *calendarController = [[CJCalendarViewController alloc] init];
    calendarController.view.frame = self.view.frame;
    calendarController.delegate = self;
    [self presentViewController:calendarController animated:YES completion:nil];
}
#pragma mark - 日历控件的代理
-(void)CalendarViewController:(CJCalendarViewController *)controller didSelectActionYear:(NSString *)year month:(NSString *)month day:(NSString *)day{
    NSLog(@"日历确定按钮点击");
    [_searchBar resignFirstResponder];
    self.searchWay = @"2";
    self.searchContent = [NSString stringWithFormat:@"%@-%@-%@",year,month,day];
    [self searchDataFromServer];
}
#pragma mark - <UISearchBarDelegate>
- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
    if (searchBar.text) {
        [_searchDataArray removeAllObjects];
        [_tableView reloadData];
    }
}


- (BOOL)searchBarShouldEndEditing:(UISearchBar *)searchBar {
    //    [self.view addSubview:_tableView];
    return YES;
}
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
    [self.searchBar resignFirstResponder];
    if([searchBar.text length] > 0) {  // 有输入
        self.searchWay = @"1";
        [self searchDataFromServer];//请求服务器
    }else { // 无输入
        return;
    }
}
- (void)popBack {
    _searchBar.text = nil;
    [_tableView removeFromSuperview];
}
#pragma mark - configUI
- (void)configTableView {
    _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 62, self.view.bounds.size.width, self.view.bounds.size.height - 62)];
    _tableView.dataSource = self;
    _tableView.delegate   = self;
    _tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
    [_tableView registerClass:[EventCell class] forCellReuseIdentifier:cellID];
    //    [self.view addSubview:_tableView];
    //    _tableView.hidden  = YES;
}
- (void)configCalendarBtn {
    _calendarBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    _calendarBtn.backgroundColor    = [UIColor lightGrayColor];
    [_calendarBtn setBackgroundImage:[UIImage imageNamed:@"btn_calendar.png"] forState:UIControlStateNormal];
    _calendarBtn.frame              = CGRectMake(self.view.bounds.size.width / 2 - 30, 100, 60, 60);
    _calendarBtn.layer.cornerRadius = 29;
    _calendarBtn.backgroundColor    = [UIColor whiteColor];
    _calendarBtn.clipsToBounds      = YES;
    [_calendarBtn addTarget:self action:@selector(calendarBtnClick)
           forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_calendarBtn];
}
#pragma mark - 发送

- (void)searchDataFromServer {
    [_searchBar resignFirstResponder];
    [self.searchDataArray removeAllObjects];
    self.searchDataArray = nil;
    if (self.tag == 1) {
        CurrentEvent *ceModel = [self.dataArray lastObject];
        self.lastEventUID = ceModel.IncidentUID;
    }else if (self.tag == 2) {
        CurrentEvent *ceModel = [self.dataArray lastObject];
        self.lastEventUID = ceModel.EventUID;
    }else if (self.tag == 3) {
        TollEvent *tollModel = [self.dataArray lastObject];
        self.lastEventUID = tollModel.EventUID;
    } else {
        ReportEvent *reportModel = [self.dataArray lastObject];
        self.lastEventUID = reportModel.IncidentUID;
    }
    NSString *searchContent ;
    if ([self.searchWay isEqualToString:@"1"]) {
        searchContent = _searchBar.text;
    }else {
        searchContent = self.searchContent;
    }
    _lastEventUID = @"";
    NSString *eventClass = [NSString stringWithFormat:@"%ld",(long)self.tag];
    RequestHelper *requestHelper=[[RequestHelper alloc] init];
    RequestGinsengModel *SearchEventModel=[[RequestGinsengModel alloc] init];
    SearchEventModel.URL         = GetEventDataURL;
    SearchEventModel.DataValue   = [self DataValueStr:_lastEventUID pageIndex:[NSString stringWithFormat:@"%ld",self.currentPageIndex] pageSize:@"10" eventClass:eventClass searchWay:_searchWay searchContent:searchContent];
    SearchEventModel.UpdatedTime = @"";
    SearchEventModel.SystemCode  = @"GuangleHighway";
    SearchEventModel.MethodName  = @"SearchEvent";
    requestHelper.block=^(RequestOutginseng *requestOutginseng,id dataValueModel){
        [_searchDataArray removeAllObjects];
        
        if (self.tag == 1 || self.tag == 2 ) {
            self.searchDataArray = [CurrentEvent mj_objectArrayWithKeyValuesArray:requestOutginseng.DataValue];
        } else if (self.tag == 3) {
            self.searchDataArray = [TollEvent mj_objectArrayWithKeyValuesArray:requestOutginseng.DataValue];
        }else {
            self.searchDataArray = [ReportEvent mj_objectArrayWithKeyValuesArray:requestOutginseng.DataValue];
        }
        if (_searchDataArray.count == 0) {
            [SVProgressHUD showSuccessWithStatus:@"没有查询到相关事件"];
        }
        if ([requestOutginseng.Code isEqualToString:@"001"]&& _searchDataArray.count >0) {
            [self.view addSubview:_tableView];
            //            _calendarBtn.hidden = YES;
            //            _tableView.hidden   = NO;
            if ([_searchWay isEqualToString:@"2"]) {
                self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"checkUserType_backward_9x15_"] style:UIBarButtonItemStylePlain target:self action:@selector(popBack)];
            }
            [_tableView reloadData];
            self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"checkUserType_backward_9x15_"] style:UIBarButtonItemStylePlain target:self action:@selector(popBack)];
            [_searchBar resignFirstResponder];
        }
    };
    [requestHelper RequestGinsengModel:SearchEventModel andPushController:self];
}
#pragma mark - dataValueString
-(NSString *)DataValueStr:(NSString *)lastEventUID pageIndex:(NSString *)pageIndex pageSize:(NSString *)pageSize eventClass:(NSString *)eventClass searchWay:(NSString *)searchWay searchContent:(NSString *)searchContent {
    NSString *valueStr =[NSString stringWithFormat:@"[{\"Key\":\"LastEventUID\",\"Value\":\"%@\"},{\"Key\":\"PageIndex\",\"Value\":\"%@\"},{\"Key\":\"PageSize\",\"Value\":\"%@\"},{\"Key\":\"EventClass\",\"Value\":\"%@\"},{\"Key\":\"SearchWay\",\"Value\":\"%@\"},{\"Key\":\"SearchContent\",\"Value\":\"%@\"}]",lastEventUID,pageIndex,pageSize,eventClass,searchWay,searchContent];
    NSLog(@"%@",valueStr);
    return valueStr;
}

#pragma mark - tableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.searchDataArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    EventCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    if (self.tag == 1) {
        CurrentEvent *ceModel = self.searchDataArray[indexPath.row];
        [cell setCellData:ceModel];
    } else if (self.tag == 2) {
        CurrentEvent *ceModel = self.searchDataArray[indexPath.row];
        [cell setCellData:ceModel];
    } else if (self.tag == 3) {
        TollEvent *tollModel = self.searchDataArray[indexPath.row];
        [cell setCellTollData:tollModel];
    }else {
        ReportEvent *reModel = self.searchDataArray[indexPath.row];
        [cell setCellReportData:reModel];
    }
    return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    CGFloat cellHeight;
    if (self.tag == 1) {
        CurrentEvent *ceModel = self.searchDataArray[indexPath.row];
        cellHeight = ceModel.searchCurrentCellH;
    }else if (self.tag == 2){
        CurrentEvent *ceModel = self.searchDataArray[indexPath.row];
        cellHeight = ceModel.searchHistoryCellH;
    }else if (self.tag == 3) {
        TollEvent *tollModel = self.searchDataArray[indexPath.row];
        cellHeight = tollModel.searchTollCellH;
    }else {
        ReportEvent *reModel = self.searchDataArray[indexPath.row];
        cellHeight = reModel.searchReportCellH;
    }
    return cellHeight;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (_tag == 1) {
        CurrentContructDetailController *vc = [[CurrentContructDetailController alloc] init];
        vc.CEModel = self.dataArray[indexPath.row];
        [self.navigationController pushViewController:vc animated:YES];
    }
    if (_tag == 2) {
        HistoryDetailViewController *vc = [[HistoryDetailViewController alloc] init];
        vc.CEModel = self.dataArray[indexPath.row];
        //        vc.fromMark = 2;
        [self.navigationController pushViewController:vc animated:YES];
        
    }
    if (_tag == 3) {
        TollViewController *vc = [[TollViewController alloc] init];
        vc.model = self.dataArray[indexPath.row];
        [self.navigationController pushViewController:vc animated:YES];
    }
    if (_tag == 4) {
        ReportEvent *model = self.dataArray[indexPath.row];
        if (model.State == 1){
            ComfirnDeatilController *comfirnVC = [[ComfirnDeatilController alloc]init];
            comfirnVC.reportModel = model;
            [self.navigationController pushViewController:comfirnVC animated:YES];
        }
        
        if (model.State == 2){
            EditDetailViewController *vc = [[EditDetailViewController alloc]init];
            vc.reportModel = model;
            [self.navigationController pushViewController:vc animated:YES];
        }
        
    }
}
@end
